﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;

using Excel;

namespace BMCShowView.Business
{
    public static class DutyLog
    {
        public class Task
        {
            public TimeSpan StartTime { get; set; }
            public TimeSpan EndTime { get; set; }
            public string Information { get; set; }
        }

        public static List<Task> ReadFromStream(Stream stream)
        {
            var result = new List<Task>();

            using (var reader = ExcelReaderFactory.CreateOpenXmlReader(stream))
            {
                reader.IsFirstRowAsColumnNames = true;

                using (var dataset = reader.AsDataSet())
                {
                    using (var table = dataset.Tables[0])
                    {
                        for (var column = 0; column < 2; ++column)
                        {
                            foreach (DataRow row in table.Rows)
                            {
                                var duration = row[0 + column * 6] as string;
                                if (duration != null && (duration.Contains('-') || duration.Contains('—')))
                                {
                                    try
                                    {
                                        var times = duration.Split('-', '—')
                                            .Select(x => TimeSpan.Parse(x.Replace('：', ':')))
                                            .ToArray();

                                        result.Add(new Task
                                        {
                                            StartTime = times[0],
                                            EndTime = times[1],
                                            Information = row[1 + column * 6].ToString()
                                        });
                                    }
                                    catch (Exception e)
                                    {
                                        Trace.TraceError("解析值班日志Excel文件出错：{0}\n{1}", row, e);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}